// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

const tool = require('ToolUtil');
module.exports = {
    _headMap: null,
    _headLoadMap: [],
    _headTextureMap: [],
    getLoadMap: function () {
        return this._headLoadMap;
    },
    initHeadMap: function () {
        var headStr = cc.sys.localStorage.getItem('headmap', '');
        if (headStr == null || headStr == '') {
            this._headMap = {};
        } else {
            this._headMap = JSON.parse(headStr);
        }
    },

    setHeadUrl: function (id, str) {
        if (this._headMap == null) {
            this.initHeadMap();
        }
        this._headMap[id] = this.str2Url(str);
    },

    getHeadUrl: function (id) {
        if (this._headMap == null) {
            this.initHeadMap();
        }
        return this._headMap[id];
    },

    saveToFile: function () {
        cc.sys.localStorage.setItem('headmap', JSON.stringify(this._headMap));
    },



    //纪录哪些头像未获取
    str2Url: function (str) {
        if (str && str.length > 0 && !str.startsWith('http://thirdwx.qlogo.cn/mmopen')) {
            return 'http://thirdwx.qlogo.cn/mmopen' + str;
        }
        return str;
    },

    url2Str: function (url) {
        if (url && url.length > 0 && url.startsWith('http://thirdwx.qlogo.cn/mmopen')) {
            return url.substring(30);
        }
        return url;
    },

    getHeadTextureByID: function (id) {
        var texture = this._headTextureMap[id];
        if (texture === undefined)
            return texture;
        if (!cc.isValid(texture)) {
            this._headTextureMap[id] = undefined;
            return undefined;
        }
        return texture;
    },
    toLoadHeadTexture: function (id, url) {
        this._headLoadMap.push(id);
        this.setHeadUrl(id, url);


        cc.loader.load({
            url: url,
            type: "png"
        }, function (err, tex) {
            if (err != null) {
                //为空
                tool.Notification.emit('headLoad' + id);
                return;
            }
            var img = new cc.SpriteFrame(tex, cc.Rect(0, 0, tex.width, tex.height));
            this._headTextureMap[id] = img;
            tool.Notification.emit('headLoad' + id, img);
        }.bind(this));

    }
};